package com.travel.modules.sys.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.travel.commons.annotation.SysLog;
import com.travel.commons.shiro.ShiroUserGetter;
import com.travel.commons.utils.BeanUtils;
import com.travel.commons.utils.HttpUtils;
import com.travel.commons.utils.R;
import com.travel.commons.validator.Assert;
import com.travel.commons.validator.ValidatorUtils;
import com.travel.commons.validator.groups.UpdateGroup;
import com.travel.modules.sys.dto.UpdatePwdDTO;
import com.travel.modules.sys.dto.UserUpdateDTO;
import com.travel.modules.sys.entity.SysUser;
import com.travel.modules.sys.entity.SysUserToken;
import com.travel.modules.sys.service.SysUserService;
import com.travel.modules.sys.service.SysUserTokenService;
import org.apache.shiro.crypto.hash.Sha256Hash;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpServletRequest;
import java.util.Map;

/**
 * 系统管理员-用户管理
 */
@RestController
@RequestMapping("/sys/user")
public class SysUserController {
    @Resource
    private SysUserService sysUserService;

    @Resource
    private SysUserTokenService sysUserTokenService;

    /**
     * 系统管理员获取所有用户
     * @param param
     *        Integer page - 当前页
     *        Integer limit - 一页显示上限
     * @return 用户列表
     */
    @RequestMapping("/list")
    public R list(@RequestBody Map<String, Object> param) {
        return R.ok().put("page",sysUserService.getUserPage(param));
    }

    /**
     * 系统管理员获取用户的详情信息
     * @param form userId
     * @return 用户详情信息
     */
    @RequestMapping("/sys/info")
    public R info(@RequestBody SysUser form) {
        return R.ok().put("page",sysUserService.getUserInfo(form.getId()));
    }

    /**
     * 获取当前登录的用户信息
     * @return 用户信息
     */
    @RequestMapping("/getInfo")
    public R getInfo() {
        return R.ok().put("page", sysUserService.getUserInfo(ShiroUserGetter.getUserId()));
    }

    /**
     * 更新用户信息
     * @param form 用户信息
     */
    @RequestMapping("/update")
    public R update(@RequestBody UserUpdateDTO form) {
        SysUser old = sysUserService.getById(form.getId());
        if (old == null) {
            return R.error("更新用户不存在");
        }
        old.setUsername(form.getUsername() != null ? form.getUsername() : old.getUsername());
        old.setHeadUrl(form.getHeadUrl() != null ? form.getHeadUrl() : old.getHeadUrl());
        old.setEmail(form.getEmail() != null ? form.getEmail() : old.getEmail());
        old.setMobile(form.getMobile() != null ? form.getMobile() : old.getMobile());
        old.setIntroduce(form.getIntroduce() != null ? form.getIntroduce() : old.getIntroduce());
        old.setSex(form.getSex() != null ? form.getSex() : old.getSex());
        old.setRealName(form.getSex() != null ? form.getRealName() : old.getRealName());
        old.setIdCard(form.getIdCard() != null ? form.getIdCard() : old.getIdCard());
        old.setAge(form.getAge() != null ? form.getAge() : old.getAge());

        if (ShiroUserGetter.getUser().getRoleId() == 1) {// 系统管理员才可以修改status
            old.setStatus(form.getStatus() != null ? form.getStatus() : old.getStatus());
        }
        sysUserService.updateById(old);
        return R.ok();
    }

    /**
     * 用户重置自己密码
     * @param form 重置密码信息：新密码，旧密码
     */
    @RequestMapping("/reset/pwd")
    public R resetPwd(@RequestBody UpdatePwdDTO form) {
        String oldPwd = form.getOldPwd();
        Assert.isBlank(oldPwd, "旧密码不能为空");
        String newPwd = form.getNewPwd();
        Assert.isBlank(newPwd, "新密码不能为空");
        //旧密码256加密对比
        SysUser user = ShiroUserGetter.getUser();
        String old256Pwd = new Sha256Hash(oldPwd, user.getSalt()).toHex();
        if (!old256Pwd.equals(user.getPassword())) {
            return R.error("旧密码与当前密码不一致");
        }
        //256加密
        user.setPassword(new Sha256Hash(newPwd, user.getSalt()).toHex());
        user.setResetPw(0);
        sysUserService.updateById(user);
        // 登出用户
        sysUserTokenService.logout(form.getUserId());
        return R.ok();
    }

    /**
     * 系统管理员重置用户密码
     * @param form 重置密码信息：用户id，新密码
     */
    @SysLog("管理员重置用户密码")
    @RequestMapping("/sys/reset/pwd")
    public R sysResetPwd(@RequestBody UpdatePwdDTO form) {
        String newPwd = form.getNewPwd();
        Assert.isBlank(newPwd, "新密码不能为空");
        //256加密
        SysUser user = sysUserService.getById(form.getUserId());
        user.setPassword(new Sha256Hash(newPwd, user.getSalt()).toHex());
        user.setResetPw(0);
        sysUserService.updateById(user);
        // 登出用户
        sysUserTokenService.logout(form.getUserId());
        return R.ok().put("id", user.getLoginName());
    }

    /**
     * 系统管理员删除用户
     * @param form userId
     */
    @SysLog("用户删除")
    @RequestMapping("/sys/del")
    public R sysDel(@RequestBody SysUser form) {
        sysUserService.removeById(form.getId());
        return R.ok();
    }

    @RequestMapping("/getRole")
    public R getRole(ServletRequest request) {
        Integer roleId = null;
        String token = HttpUtils.getToken((HttpServletRequest) request);
        SysUserToken sysUserToken  = sysUserTokenService.getOne(new QueryWrapper<SysUserToken>().eq("token", token));
        if (sysUserToken != null) {
            roleId = sysUserService.getById(sysUserToken.getUserId()).getRoleId();
        }
        return R.ok().put("roleId", roleId);
    }
}
